<template>
  <!-- 冷铁需求详情表单弹窗 -->
  <el-dialog
    v-model="visibleDialog"
    :title="props.title"
    width="85%"
    draggable
    @close="closeDialog"
  >
    <el-form
      ref="formRef"
      :model="formData"
      :inline="true"
      :rules="rules"
      label-width="80"
    >
      <el-row>
        <el-col :span="4">
          <el-form-item label="日期" prop="planActualDate">
            <el-date-picker
              v-model="formData.planActualDate"
              type="date"
              value-format="YYYY-MM-DD"
              placeholder="请选择日期"
              @change="getPlanWorkingForm"
            />
          </el-form-item>
        </el-col>
        <el-col :span="2">
          <el-form-item label="">
            <el-button type="primary" @click="getPlanWorkingForm"
              >查询</el-button
            >
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="班组" prop="crewId">
            <el-select
              v-model="formData.crewId"
              placeholder="请选择班组"
              @change="changeCrew"
              clearable
            >
              <el-option
                v-for="item in crewList"
                :key="item.id"
                :label="item.crewName"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-card shadow="never" class="table-container">
        <div class="formTable2">
          <el-table
            max-height="710"
            :data="formData.details"
            :key="Math.random"
            border
            style="width: 100%"
            :cell-style="cellStyle"
          >
            <el-table-column
              type="index"
              label="序号"
              align="center"
              width="80"
            />
            <el-table-column
              label="计划编号"
              prop="processingOrderNumber"
              min-width="180"
              show-overflow-tooltip
            />
            <el-table-column
              label="产品图号"
              prop="figureNumber"
              min-width="170"
              show-overflow-tooltip
            />
            <el-table-column
              label="产品名称"
              prop="materialName"
              min-width="180"
              show-overflow-tooltip
            >
              <template #default="scope">
                {{ scope.row.materialName }}
              </template>
            </el-table-column>
            <el-table-column
              label="生产日期"
              prop="planActualDate"
              min-width="140"
              align="center"
            >
              <template #default="{ $index, row }">
                <el-form-item
                  :prop="'details.' + $index + '.planActualDate'"
                  :rules="rules.planActualDate"
                  label-width="0"
                  style="width: 100%"
                >
                  <el-date-picker
                    v-model="row.planActualDate"
                    type="date"
                    value-format="YYYY-MM-DD"
                    placeholder="请选择生产日期"
                    :disabled-date="disabledDate"
                    @change="changePlanActualDate(row)"
                  />
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column
              label="计划数量"
              prop="planQuantity"
              min-width="100"
              show-overflow-tooltip
              header-align="center"
              align="right"
            />
            <el-table-column
              label="生产批次号"
              prop="plannedBatch"
              min-width="100"
              show-overflow-tooltip
            />
            <el-table-column
              label="上工序完成时间"
              prop="lastProcessFinshTime"
              min-width="160"
              show-overflow-tooltip
              align="center"
            />
            <el-table-column label="计划人员" props="planUsers" min-width="380">
              <template #default="{ $index, row }">
                <el-form-item
                  :prop="'details.' + $index + '.planUserIds'"
                  :rules="rules.sonplanUserIds"
                  label-width="0"
                  style="width: 100%"
                >
                  <el-select
                    v-model="row.memberIds"
                    placeholder="请选择计划人员"
                    clearable
                    style="width: 100%"
                    @change="changePlanUser(row, $index)"
                    filterable
                    multiple
                    collapse-tags-tooltip
                    :max-collapse-tags="1"
                  >
                    <el-option
                      v-for="item in memberList"
                      :key="item.id"
                      :label="`${item.memberName}`"
                      :value="item.memberId"
                    />
                  </el-select>
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column
              label="理论时长/分"
              prop="theoreticalTime"
              min-width="120"
              show-overflow-tooltip
              align="center"
            >
              <template #default="{ row }">
                {{
                  row.memberIds.length
                    ? Math.round(
                        row.theoreticalTime / 60 / row.memberIds?.length
                      )
                    : Math.round(row.theoreticalTime / 60)
                }}
              </template>
            </el-table-column>
            <el-table-column
              label="计划开始时间"
              prop="planBeginTime"
              min-width="200"
              align="center"
            >
              <template #default="{ $index, row }">
                <el-form-item
                  :prop="'details.' + $index + '.planBeginTime'"
                  :rules="rules.sonplanBeginTime"
                  label-width="0"
                  style="width: 100%"
                >
                  <el-date-picker
                    v-model="row.planBeginTime"
                    type="datetime"
                    placeholder="请选择开始时间"
                    format="YYYY-MM-DD HH:mm:ss"
                    :disabled-date="disabledDate"
                    @change="queryTimeEndOne(row, $index)"
                  />
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column
              label="计划结束时间"
              prop="planEndTime"
              min-width="160"
              show-overflow-tooltip
              align="center"
            />
          </el-table>
        </div>
      </el-card>
    </el-form>

    <template #footer>
      <div class="dialog-footer">
        <el-button type="primary" :loading="loading" @click="handleSubmit"
          >提 交</el-button
        >
        <el-button type="primary" :loading="loading" @click="save"
          >保 存</el-button
        >
        <el-button @click="closeDialog">取 消</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import request from "@/utils/request";
import { useDictStoreHook } from "@/store/modules/dictionary";
const dictionaryStore = useDictStoreHook();

defineOptions({
  name: "USERTIME",
  inheritAttrs: false,
});

const emit = defineEmits(["reset-table", "change-visible"]);

const props = defineProps({
  visible: {
    type: Boolean,
    default: () => {
      return false;
    },
  },
  title: {
    type: String,
    default: () => {
      return "";
    },
  },
  data: {
    type: Object,
    default: () => {
      return {};
    },
  },
  isReadonly: {
    type: Boolean,
    default: () => {
      return false;
    },
  },
  isPm: {
    type: Boolean,
    default: () => {
      return false;
    },
  },
});

const visibleDialog = ref(false);
watch(
  () => props.visible,
  (newVal: boolean) => {
    visibleDialog.value = newVal;
    getPlanWorkingForm();
    setTimeout(() => {
      formRef.value.clearValidate();
    }, 50);
  }
);
const validateTime = (rule, value) => {
  //保存时统一校验
  console.log(rule);
  const t3 = new Date(value).getTime();

  return Promise.resolve();
};

const rules = reactive({
  sonplanUserIds: [
    { required: true, message: "请输入计划人员", trigger: "change" },
    // {
    //   validator: validateUserIds,
    //   trigger: ["blur", "change"],
    // },
  ],
  sonplanBeginTime: [
    { required: true, message: "请选择计划开始时间", trigger: "change" },
    {
      validator: validateTime,
      trigger: ["blur", "change"],
    },
  ],
  planActualDate: [
    { required: true, message: "请选择生产日期", trigger: "change" },
  ],
});
function validateDegree(rule: any, value: any, callback: (a?: any) => {}) {
  if (isNaN(parseFloat(value)) && isFinite(value)) {
    callback(new Error("请输入整数"));
  } else if (!/^[+-]?\d+?(e[+-]?\d+)?$/.test(value)) {
    callback(new Error("请输入整数"));
  } else if (Number(value) < 0) {
    callback(new Error("请输入大于0的整数"));
  } else {
    callback();
  }
}
const formRef = ref(ElForm);

let formData = reactive({
  details: [],
  crewId: "",
  crewName: "",
  planActualDate: getCurrentDate(),
  // planActualDate: "2025-04-17",
});

watch(
  () => props.data,
  (newVal: any) => {
    // const { details } = newVal;
    // formData.details = details;
    // // Object.assign(formData, {
    // //   details,
    // // });
    // if (details?.length > 0) {
    //   getCrews();
    //   formData.details.forEach((item) => {
    //     if (item.planUserIds) {
    //       item.memberIds = item.planUserIds.split(",");
    //     }
    //   });
    //   if (details[0].crewId) {
    //     formData.crewId = details[0].crewId;
    //     getCrewMembers();
    //   }
    // }
  }
);

/** 关闭表单弹窗 */
function closeDialog() {
  visibleDialog.value = false;
  emit("change-visible", false);
  resetForm();
}

/** 重置表单 */
function resetForm() {
  formRef.value.resetFields();
  formRef.value.clearValidate();
  formData.details = [];
  formData.crewId = "";
  formData.crewName = "";
  memberList.value = [];
}

const loading = ref(false);

function handleSubmit() {
  for (let index = 0; index < formData.details.length; index++) {
    let item = formData.details[index];
    if (!item.planEndTime) {
      ElMessage.error("计划结束时间不能为空！");
      return;
    }
    if (index == 0) {
      const t1 = new Date(item.lastProcessFinshTime).getTime();
      const t2 = new Date(item.planBeginTime).getTime();
      if (Math.sign(t2 - t1) < 0) {
        ElMessage.error(
          `第 ${index + 1} 行,的计划开始时间不能小于工序完成时间！`
        );
        flag = true;
        return;
      }
    }
    if (index != 0) {
      const t1 = new Date(item.lastProcessFinshTime).getTime();
      const t2 = new Date(item.lastProcessFinshTime).getTime();
      const t3 = new Date(item.planBeginTime).getTime();
      const t4 = new Date(
        Math.sign(t1 - t2) > 0
          ? item.lastProcessFinshTime
          : item.lastProcessFinshTime
      ).getTime();
      if (Math.sign(t3 - t4) < 0) {
        ElMessage.error(
          `第 ${index + 1} 行,计划开始时间不能小于工序完成时间！`
        );
        flag = true;
        return;
      }
    }
  }
  formRef.value.validate(async (valid: any) => {
    if (valid) {
      loading.value = true;
      const text = "人员指派提交";
      await request({
        url: "/mes/mesplanworkingform/saveBurnish",
        method: "post",
        data: {
          listWorkingForm: formData.details,
          planDate: formData.planActualDate,
        },
      }).finally(() => {
        loading.value = false;
      });
      ElMessage.success(text + `成功`);
      closeDialog();
      emit("reset-table", formData);
    }
  });
}
function save() {
  for (let index = 0; index < formData.details.length; index++) {
    let item = formData.details[index];
    if (!item.planEndTime) {
      ElMessage.error("计划结束时间不能为空！");
      return;
    }
    if (index == 0) {
      const t1 = new Date(item.lastProcessFinshTime).getTime();
      const t2 = new Date(item.planBeginTime).getTime();
      if (Math.sign(t2 - t1) < 0) {
        ElMessage.error(
          `第 ${index + 1} 行,的计划开始时间不能小于工序完成时间！`
        );
        flag = true;
        return;
      }
    }
    if (index != 0) {
      const t1 = new Date(item.lastProcessFinshTime).getTime();
      const t2 = new Date(item.lastProcessFinshTime).getTime();
      const t3 = new Date(item.planBeginTime).getTime();
      const t4 = new Date(
        Math.sign(t1 - t2) > 0
          ? item.lastProcessFinshTime
          : item.lastProcessFinshTime
      ).getTime();
      if (Math.sign(t3 - t4) < 0) {
        ElMessage.error(
          `第 ${index + 1} 行,计划开始时间不能小于工序完成时间！`
        );
        flag = true;
        return;
      }
    }
  }
  formRef.value.validate(async (valid: any) => {
    if (valid) {
      loading.value = true;
      const text = "人员指派保存";
      await request({
        url: "/mes/mesplanworkingform/userAssign",
        method: "post",
        data: formData.details,
      }).finally(() => {
        loading.value = false;
      });
      ElMessage.success(text + `成功`);
      closeDialog();
      emit("reset-table", formData);
    }
  });
}
// 组件销毁时调用
onBeforeUnmount(() => {
  visibleDialog.value = false;
  emit("change-visible", false);
});

//时间格式处理，yyyy-mm-dd
function formatDate(row, column) {
  const date = row[column.property];
  if (!date) return "";
  return date.split(" ")[0]; // 返回日期的年月日部分，而隐藏时间部分
}
const crewList = ref([]);
async function getCrews() {
  await request({
    url: "mes/mescrew/getCrew",
    method: "post",
    data: {
      plantId: formData.plantId,
      enabled: 1,
    },
  }).then((res) => {
    crewList.value = res.data;
  });
}
function changeCrew(val) {
  formData.crewId = val;
  formData.crewName = "";
  memberList.value = [];
  formData.details.forEach((item) => {
    item.planUserIds = "";
    item.planUsers = "";
    item.memberIds = [];
    item.planEndTime = "";
  });
  if (val) {
    let crew = crewList.value.find((item) => item.id == val);
    formData.crewName = crew.crewName;
    getCrewMembers();
  }
}
//人员
const memberList = ref([]);
async function getCrewMembers() {
  await request({
    url: "mes/mescrew/getCrewMembers",
    method: "post",
    data: {
      id: formData.crewId,
    },
  }).then((res) => {
    memberList.value = res.data;
  });
}
//人员
const changePlanUser = (row: any, index: number) => {
  row.planUserIds = row.memberIds.join(",");
  let materialNameList = [];
  row.memberIds.forEach((item: any) => {
    memberList.value.forEach((i) => {
      if (item === i.memberId) {
        materialNameList.push(i.memberName);
      }
    });
  });
  row.planUsers = materialNameList.join(",");
  // changePlanBeginTime(row);

  queryTimeEndOne(row, index);
};
// 获取当前日期yyyymmdd
function getCurrentDate(time?: any) {
  let today = new Date();
  if (time) {
    today = new Date(time);
  }
  let year = today.getFullYear();
  let month = (today.getMonth() + 1).toString().padStart(2, "0");
  let day = today.getDate().toString().padStart(2, "0");
  return year.toString() + "-" + month + "-" + day;
}
async function getPlanWorkingForm() {
  if (!formData.planActualDate) {
    ElMessage.error("请选择日期");
    return;
  }
  request({
    url: `/mes/mesplanworkingform/queryByList`,
    method: "post",
    data: {
      planActualDate: formData.planActualDate,
      processesClassification: props.data.processesClassification,
      isASC: 1,
    },
  })
    .then((res) => {
      // formData.details = res.data;
      // queryTimeEnd(res.data);
      formData.details = res.data;
      if (formData.details.length > 0) {
        getCrews();
        formData.details.forEach((item, index) => {
          item.index = index;
          if (item.planUserIds) {
            item.memberIds = item.planUserIds.split(",");
          } else {
            item.memberIds = [];
          }
        });
        if (formData.details[0].crewId) {
          formData.crewId = formData.details[0].crewId;
          getCrewMembers();
        }
      }
    })
    .catch((res) => {
      console.log(res);
    });
  formRef.value.clearValidate();
}
function changePlanBeginTime(row: any) {
  if (row.planBeginTime && row.theoreticalTime) {
    row.planEndTime = calculateDuration(
      row.planBeginTime,
      row.theoreticalTime,
      row.memberIds?.length
    );
  }
}
function calculateDuration(beginTime, time, length) {
  const start = new Date(beginTime);
  let number = 0;
  if (length && length > 0) {
    number = Math.round(time / 60 / length) * 60 * 1000;
  } else {
    number = time * 1000;
  }
  const extendedDate = new Date(start.valueOf() + number);
  const year = extendedDate.getFullYear();
  const month = String(extendedDate.getMonth() + 1).padStart(2, "0");
  const day = String(extendedDate.getDate()).padStart(2, "0");
  const hours = String(extendedDate.getHours()).padStart(2, "0");
  const minutes = String(extendedDate.getMinutes()).padStart(2, "0");
  const seconds = String(extendedDate.getSeconds()).padStart(2, "0");
  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
}

function queryTimeEnd(list) {
  request({
    url: `/mes/mesplanworkingform/queryTimeEnd`,
    method: "post",
    data: list,
  })
    .then((res) => {
      formData.details = res.data;
      if (formData.details.length > 0) {
        getCrews();
        formData.details.forEach((item, index) => {
          item.index = index;
          if (item.planUserIds) {
            item.memberIds = item.planUserIds.split(",");
          } else {
            item.memberIds = [];
          }
        });
        if (formData.details[0].crewId) {
          formData.crewId = formData.details[0].crewId;
          getCrewMembers();
        }
      }
    })
    .catch((res) => {
      console.log(res);
    });
}
async function queryTimeEndOne(row, index) {
  row.planActualDate = getCurrentDate(row.planEndTime);
  await request({
    url: `/mes/mesplanworkingform/queryTimeEnd`,
    method: "post",
    data: [row],
  })
    .then((res) => {
      row.theoreticalTime = res.data[0].theoreticalTime;
      row.planEndTime = res.data[0].planEndTime;
      row.planActualDate = res.data[0].planActualDate;
      if (index != 0 && formData.details[index - 1]?.planEndTime) {
        let t1 = new Date(row.planBeginTime).getTime();
        let t2 = new Date(formData.details[index - 1].planEndTime).getTime();
        row.isChangeColor = Math.sign(t1 - new Date(t2 + 300000)) > 0;
      }
    })
    .catch((res) => {
      row.planEndTime = "";
    });
}

async function queryTimeEndOneTime(row) {
  if (formData.details.length > 0) {
    formData.details.forEach((item, index) => {
      if (index == 0) {
        const t1 = new Date(item.lastProcessFinshTime).getTime();
        const t2 = new Date(row.planBeginTime).getTime();
        if (Math.sign(t1 - t2) > 0) {
          item.planBeginTime = item.lastProcessFinshTime;
          row.planBeginTime = item.planBeginTime;
        }
        queryTimeEndOne(row);
      }
      if (index != 0) {
        const t1 = new Date(formData.details[index - 1].planEndTime).getTime();
        const t2 = new Date(item.lastProcessFinshTime).getTime();
        console.log("t1", formData.details[index - 1].planEndTime);
        console.log("t2", item.lastProcessFinshTime);
        console.log(Math.sign(t1 - t2) > 0);
        item.planBeginTime =
          Math.sign(t1 - t2) > 0
            ? formData.details[index - 1].planEndTime
            : item.lastProcessFinshTime;
        queryTimeEndOne(item);
      }
    });
  }
}
function getStartEndTime(row) {
  request({
    url: `/mes/mesplanworkingform/queryTimeEnd`,
    method: "post",
    data: [row],
  })
    .then((res) => {
      row.planEndTime = res.data[0].planEndTime;
    })
    .catch((res) => {
      console.log(res);
    });
}
const disabledDate = (time: Date) => {
  let date = new Date(formData.planActualDate);
  date.setDate(date.getDate() - 1);
  return new Date(time).getTime() <= date.getTime();
};
function changePlanActualDate(row: any) {
  row.planBeginTime = "";
  row.planEndTime = "";
  row.isChangeColor = false;
}
const cellStyle = (data) => {
  if (data.row.isChangeColor) {
    return {
      color: "#000",
      background: "#FBE2E2",
    };
  }
};
</script>
